# -*- coding: utf-8 -*-
# @Time    : 2024/8/15 08:50
# @Author  : Zhangjian
# @File    : LuckGitlabProjectService.py

from luck.gitlab.LuckGitlabApi import LuckGitlabApi
import pymysql
import threading
import re


class LuckGitlabProjectService(object):

    def __init__(self, config):
        self.config = config
        self.gitlab_api = LuckGitlabApi(self.config["gitlab_private_token"], self.config["gitlab_server_url"])
        self.db_config = {
            'host': self.config["db_host"],
            'port': self.config["db_port"],
            'user': self.config["db_user"],
            'password': self.config["db_password"],
            'database': self.config["db_name"]
        }

    # 权限级别翻译字典
    access_level_descriptions = {
        10: "Guest (访客)",
        20: "Reporter (报告者)",
        30: "Developer (开发者)",
        40: "Maintainer (维护者)",
        50: "Owner (所有者)"
    }

    # 获取用户名对应的中文名
    def get_chinese_name(self, username):
        try:
            connection = pymysql.connect(**self.db_config)
            with connection.cursor(pymysql.cursors.DictCursor) as cursor:
                # 查询匹配 user_username 或 commit_author_account 字段的记录
                sql = """
                SELECT user_username, user_name, commit_author_account
                FROM luck_gitlab_user
                WHERE user_username = %s OR FIND_IN_SET(%s, commit_author_account)
                """
                cursor.execute(sql, (username, username))
                result = cursor.fetchall()
                if result:
                    # 返回所有匹配的中文名，格式为 中文名(用户名)
                    return ', '.join([f"{row['user_name']}({row['user_username']})" for row in result])
                else:
                    # 如果找不到匹配，返回用户名本身
                    return f"{username}({username})"
        except Exception as e:
            print(f"Error fetching Chinese name for {username}: {e}")
            return f"{username}({username})"
        finally:
            connection.close()

    # 获取项目访问权限、最后更新信息和描述
    def get_project_info(self, project_path):
        try:
            # 获取项目对象
            project = self.gitlab_api.gl.projects.get(project_path)
            # 获取项目访问权限
            members = project.members.list()
            permissions = {
                self.get_chinese_name(member.username): self.access_level_descriptions.get(member.access_level,
                                                                                           'Unknown')
                for member in members}
            # 获取最后更新时间和最后更新者
            last_updated_at = project.last_activity_at
            last_commit = project.commits.list(per_page=1)[0]
            last_updated_by = self.get_chinese_name(last_commit.author_name) if last_commit else 'Unknown'
            # 获取项目描述
            project_description = project.description
            return permissions, last_updated_at, last_updated_by, project_description
        except Exception as e:
            print(f"Error fetching information for {project_path}: {e}")
            return None, None, None, None

    # 更新权限、最后更新信息和描述到数据库的函数
    def update_permissions(self, record):
        try:
            connection = pymysql.connect(**self.db_config)
            with connection.cursor() as cursor:
                git_info = record['GIT']
                # 使用正则表达式分割不同的分隔符
                git_urls = re.split(r'[;,\s\xa0]+', git_info)  # 支持分号、逗号、空格和全角空格
                acl_info = []
                last_info = []
                snotes_info = []

                for git_url in git_urls:
                    if git_url:
                        project_path = git_url.split('/')[3:]  # 示例提取项目路径
                        project_path = '/'.join(project_path)
                        permissions, last_updated_at, last_updated_by, project_description = self.get_project_info(
                            project_path)

                        if permissions is None:
                            acl_info.append(f"{git_url}: 获取权限异常，请检查Git路径配置")
                            last_info.append(f"{git_url}: 获取更新信息异常，请检查Git路径配置")
                        else:
                            if len(git_urls) == 1:
                                acl_info.append(', '.join([f'{user}: {level}' for user, level in permissions.items()]))
                                last_info.append(f"{last_updated_at} by {last_updated_by}")
                                snotes_info.append(project_description)
                            else:
                                acl_info.append(
                                    f"{git_url}: {', '.join([f'{user}: {level}' for user, level in permissions.items()])}")
                                last_info.append(f"{git_url}: {last_updated_at} by {last_updated_by}")
                                snotes_info.append(f"{git_url}: {project_description}")

                acl_combined = '; '.join(acl_info)
                last_combined = '; '.join(last_info)
                snotes_combined = '; '.join(snotes_info)

                sql = "UPDATE lucksoft_project SET acl = %s, last = %s, snotes = %s WHERE id = %s"
                cursor.execute(sql, (acl_combined, last_combined, snotes_combined, record['id']))
                connection.commit()
        except Exception as e:
            print(f"Error updating permissions for record {record['id']}: {e}")
        finally:
            connection.close()

    # 处理每一条记录的函数
    def process_record(self, record):
        self.update_permissions(record)

    # 获取所有需要处理的记录
    def fetch_records(self):
        try:
            connection = pymysql.connect(**self.db_config)
            with connection.cursor(pymysql.cursors.DictCursor) as cursor:
                sql = "SELECT id, GIT FROM lucksoft_project WHERE GIT IS NOT NULL"
                cursor.execute(sql)
                return cursor.fetchall()
        except Exception as e:
            print(f"Error fetching records: {e}")
        finally:
            connection.close()
        return []

    # 主函数
    def main(self):
        records = self.fetch_records()
        threads = []
        for record in records:
            if len(threads) >= 10:  # 限制同时运行的线程数
                for thread in threads:
                    thread.join()  # 等待所有线程完成
                threads = []
            thread = threading.Thread(target=self.process_record, args=(record,))
            thread.start()
            threads.append(thread)
        # 等待最后一批线程完成
        for thread in threads:
            thread.join()
